package dataBase;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CodeTitleTable extends SqlTable {

	public CodeTitleTable(String tableName,
			List<ColumnValue> schema, String engine) {
		super(tableName, schema, engine);
	}

	public Map<String,String> getTitlesByCids(Statement stmt, List<String> cidList) {
		if ((stmt == null) || (cidList == null)){
			return null;
		}
		String searchQuery = "SELECT * FROM " + tableName + " WHERE ";
		for (int i=0; i < cidList.size(); i++) {
			searchQuery += "(cid = " + cidList.get(i) + ")";
			if (i< cidList.size()-1){
				searchQuery += " OR ";  
			}
		}
		searchQuery += ";";
		try {
			ResultSet rs = stmt.executeQuery(searchQuery);
			Map<String,String> result = new HashMap<String,String>();
			while(rs.next()){
				result.put((String)rs.getObject("cid"), (String)rs.getObject("title"));
			}
			return result;
		} catch (SQLException e) {
			return null;
		}
	}
	
	/**
	 * 
	 * @param title
	 * @return relevant CID or null no such title exists
	 */
	public String searchByTitle(Statement stmt, String title) {
		if ((stmt == null) || (title == null)){
			return null;
		}
		String query = "SELECT * FROM " + tableName + " WHERE title = '" + title + "';";
		try {
			ResultSet rs = stmt.executeQuery(query);
			if (rs.next()){
				return (String)rs.getObject("cid");
			}
			return null;
		}
		catch (Exception e) {
			return null;
		}
	}

	public String getTitle(Statement stmt, String cid) {
		if ((stmt == null) || (cid == null)){
			return null;
		}
		String query = "SELECT title FROM " + tableName + " WHERE cid = '" + cid + "';";
		try {
			ResultSet rs = stmt.executeQuery(query);
			if (rs.next()){
				return (String)rs.getObject("title");
			}
			return null;
		}
		catch (Exception e) {
			return null;
		}
	}
}
